import React, { useEffect } from 'react';
import { useState } from 'react';
import api from './api/api';
import { ToastContainer, Toast } from 'react-bootstrap';
import EditDescription from './EditDescription';
import { useHistory, useParams } from 'react-router-dom/cjs/react-router-dom';
import { Button, Spinner } from 'react-bootstrap';

const EditEpisode = () => {

  const { id } = useParams();
  const history = useHistory();
  const [isLoading, setIsLoading] = useState(true);
  const [isUploading, setIsUploading] = useState(false);
  const [episode, setEpisode] = useState({});
  const [title, setTitle] = useState('');
  const [description, setDescription] = useState('');
  const [cover, setCover] = useState('');
  const [audio, setAudio] = useState('');
  const [toastShow, setToastShow] = useState(false);
  const [toastContent, setToastContent] = useState('');

  const handleSubmit = async () => {
    setIsUploading(true);
    const body = {};
    if (title)
      body.title = title;
    if (description)
      body.description = description;
    try {
      const response = await api.put(`/episodes/${id}`, body);
      if (cover) {
        const coverFormData = new FormData();
        coverFormData.append('cover_update', cover);
        const coverUploadResponse = await api.put(`episodes/${id}/cover`, coverFormData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        });
      }
      if (audio) {
        const audioFormData = new FormData();
        audioFormData.append('audio_update', audio);
        const audioUploadResponse = await api.put(`episodes/${id}/audio`, audioFormData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        });
      }
      setToastContent("修改成功！");
      setTimeout(() => {
        history.push(`/episodes/${id}`);
      }, 2000);
    } catch (error) {
      setToastContent(`修改失败：${error.message}`);
      console.log(error);
    } finally {
      setIsUploading(false);
      setToastShow(true);
      setTimeout(() => {
        setToastShow(false);
      }, 2000);
    }
  };

  useEffect(() => {
    const getPodcast = async () => {
      try {
        const response = await api.get(`/episodes/${id}`);
        const returnedEpisode = response.data;
        setEpisode(returnedEpisode);
        setIsLoading(false);
        setDescription(returnedEpisode.description);
      } catch (error) {
        console.log(error);
      }
    };
    getPodcast();
  }, [id]);

  return (
    <div className='
        container
        min-h-100
        flex-fill'
    >
      <div className="container d-flex flex-column align-items-center">
        <h1 className='mt-2 mb-5'>编辑单集</h1>
        {!isLoading &&
          <form className='mb-2' onSubmit={(e) => e.preventDefault()}>
            <div className="mb-3">
              <label for="title" className="form-label">单集名称</label>
              <input type="text" className="form-control" id="title" placeholder={episode.title} onChange={(e) => setTitle(e.target.value)} />
            </div>
            <div className='mb-3'>
              <label for="description" className="form-label">描述</label>
              <EditDescription description={description} setDescription={setDescription} />
            </div>
            <div className="mb-3">
              <label for="cover" className="form-label">封面</label>
              <input type="file" accept='image/*' className="form-control" id="cover" onChange={(e) => setCover(e.target.files[0])} />
              <div className="form-text">请选择正方形尺寸图片。</div>
            </div>
            <div className="mb-3">
              <label for="audio" className="form-label">音频</label>
              <input type="file" accept='audio/mpeg' className="form-control" id="audio" onChange={(e) => setAudio(e.target.files[0])} />
              <div className="form-text">目前仅支持 MP3 格式。</div>
            </div>
            <div className="text-center mb-4">
              <Button variant="primary" onClick={handleSubmit} disabled={isUploading ? true : false}>
                {isUploading ?
                  <>
                    <Spinner
                      as="span"
                      animation="grow"
                      size="sm"
                      role="status"
                      aria-hidden="true"
                    />
                    上传中...
                  </> :
                  <>提交</>
                }
              </Button>
            </div>

          </form>
        }
      </div>
      <ToastContainer position='middle-center' className='m-2'>
        <Toast show={toastShow} onClose={() => { setToastShow(false); }}>
          <Toast.Header>
            <img src="holder.js/20x20?text=%20" className="rounded me-2" alt="" />
            <strong className="me-auto">雨呓</strong>
          </Toast.Header>
          <Toast.Body>{toastContent}</Toast.Body>
        </Toast>
      </ToastContainer>
    </div>
  );
};

export default EditEpisode;
